/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * KoordinatorGUI.java
 *
 * Created on 09.11.2009, 14:31:21
 */
package koordinator;

import ggt.unit;

import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import koordinator.Koordinator_State.states;
import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.NotFound;

/**
 *
 * @author pascal
 */
public class KoordinatorGUI extends javax.swing.JFrame {

    // Connecting infos
    private final String host = "lab21";
    private final String port = "10500";
    
    private Koordinator koordinator;
    private Koordinator_State koordState;


    /** Creates new form KoordinatorGUI */
    private KoordinatorGUI() {
        koordState = new Koordinator_State();
        koordState.setWindow(this);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        state_label = new javax.swing.JLabel();
        current_state_label = new javax.swing.JLabel();
        state_button = new javax.swing.JButton();
        processAmountLabel = new javax.swing.JLabel();
        delay_label = new javax.swing.JLabel();
        timeout_label = new javax.swing.JLabel();
        minGGTProcesses = new javax.swing.JTextField();
        minDelayField = new javax.swing.JTextField();
        timeoutField = new javax.swing.JTextField();
        ggTLabel = new javax.swing.JLabel();
        ggTFiel = new javax.swing.JTextField();
        maxGGTProcesses = new javax.swing.JTextField();
        processAmountLabel1 = new javax.swing.JLabel();
        delay_label1 = new javax.swing.JLabel();
        maxDelayField = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ggtProzessTextArea = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        messageTextArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Koordinator");

        state_label.setText("Status: ");

        current_state_label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        current_state_label.setText("preinitial");
        current_state_label.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        state_button.setText("INIT");
        state_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                state_buttonActionPerformed(evt);
            }
        });

        processAmountLabel.setText("min. Proz.");

        delay_label.setText("min. Delay:");

        timeout_label.setText("Timeout:");

        minGGTProcesses.setText("3");

        minDelayField.setText("1");

        timeoutField.setText("5");

        ggTLabel.setText("ggT:");

        ggTFiel.setText("31415");

        maxGGTProcesses.setText("3");

        processAmountLabel1.setText("max. Proz.");

        delay_label1.setText("max. Delay:");

        maxDelayField.setText("2");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("ggt-Prozesse"));

        ggtProzessTextArea.setColumns(1);
        ggtProzessTextArea.setRows(5);
        ggtProzessTextArea.setBorder(null);
        jScrollPane1.setViewportView(ggtProzessTextArea);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Nachrichten"));

        messageTextArea.setColumns(20);
        messageTextArea.setRows(5);
        messageTextArea.setBorder(null);
        jScrollPane2.setViewportView(messageTextArea);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(delay_label, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(processAmountLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 64, Short.MAX_VALUE)
                            .addComponent(timeout_label, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(4, 4, 4)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(timeoutField)
                            .addComponent(minDelayField, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(minGGTProcesses, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(processAmountLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)
                            .addComponent(delay_label1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(ggTLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(maxGGTProcesses)
                            .addComponent(ggTFiel, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                            .addComponent(maxDelayField)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(state_label, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(current_state_label, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE))
                            .addComponent(state_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(processAmountLabel)
                    .addComponent(minGGTProcesses, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(processAmountLabel1)
                    .addComponent(maxGGTProcesses, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(delay_label)
                    .addComponent(minDelayField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(delay_label1)
                    .addComponent(maxDelayField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(ggTFiel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(ggTLabel))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(timeout_label)
                        .addComponent(timeoutField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                            .addComponent(current_state_label)
                            .addComponent(state_label))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(state_button))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void state_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_state_buttonActionPerformed
        new Thread(new Runnable() {

            public void run() {
                change_state();
            }
        }).start();
    }//GEN-LAST:event_state_buttonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new KoordinatorGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel current_state_label;
    private javax.swing.JLabel delay_label;
    private javax.swing.JLabel delay_label1;
    private javax.swing.JTextField ggTFiel;
    private javax.swing.JLabel ggTLabel;
    private javax.swing.JTextArea ggtProzessTextArea;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField maxDelayField;
    private javax.swing.JTextField maxGGTProcesses;
    private javax.swing.JTextArea messageTextArea;
    private javax.swing.JTextField minDelayField;
    private javax.swing.JTextField minGGTProcesses;
    private javax.swing.JLabel processAmountLabel;
    private javax.swing.JLabel processAmountLabel1;
    private javax.swing.JButton state_button;
    private javax.swing.JLabel state_label;
    private javax.swing.JTextField timeoutField;
    private javax.swing.JLabel timeout_label;
    // End of variables declaration//GEN-END:variables

    //###########################################
    // CUSTOM
    //###########################################
    private void change_state() {
        if (state_button.getText().equalsIgnoreCase("init")) {
            koordState.toINITIALState();
        } else if (state_button.getText().equalsIgnoreCase("ready")) {
            koordState.toREADYState();
        } else if (state_button.getText().equalsIgnoreCase("start")) {
            koordState.toSTARTState();
        }  else if (state_button.getText().equalsIgnoreCase("reset")) {
            koordState.reset();
        }
    }

    /**
     * Updates the state in the gui and sets the 
     * text in the statebutton to move one state further
     * 
     * @param state the current state of the koordinator
     * @param stateButtonText the text to display in the button for the next state
     */
    public void setState(states state, String stateButtonText) {
        current_state_label.setText(state.toString());
        state_button.setText(stateButtonText);
    }

    protected void initORB() {
        String[] args = new String[]{};
        Properties props = new Properties();
        props.put("org.omg.CORBA.ORBInitialHost", host);
        props.put("org.omg.CORBA.ORBInitialPort", port);
        ORB orb = ORB.init(args, props);

        NamingContext ctx;
        try {

            ctx = NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService"));
            // Creating koordinator and connect
            koordinator = new Koordinator(ctx);
            koordState.setKoordinator(koordinator);
            koordinator.setGUI(this);

            orb.connect(koordinator);

            NameComponent name[] = new NameComponent[]{new NameComponent(
                "chef", "")};

            ctx.rebind(name, koordinator);
            
            koordinator.logAndWrite(Level.INFO, "Connected to namingservice!");

        } catch (InvalidName e) {
            // e.printStackTrace();
            koordinator.showMessageError("InvalidName", e.getMessage());
        } catch (NotFound e) {
            // e.printStackTrace();
            koordinator.showMessageError("NotFound", e.getMessage());
        } catch (CannotProceed e) {
            // e.printStackTrace();
            koordinator.showMessageError("CannotProceed", e.getMessage());
        } catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) {
            // e.printStackTrace();
            koordinator.showMessageError("NamingContextPackage.InvalidName", e.getMessage());
        }
    }
    
    /**
     * Get all values from gui and forward into koordinator
     */
    public void collectValues(){
    	int minDelay = Integer.parseInt(this.minDelayField.getText());
    	int maxDelay = Integer.parseInt(this.maxDelayField.getText());
    	int minGGTProcesses = Integer.parseInt(this.minGGTProcesses.getText());
    	int maxGGTProcesses = Integer.parseInt(this.maxGGTProcesses.getText());
    	int timeout = Integer.parseInt(this.timeoutField.getText());
    	int ggt = Integer.parseInt(this.ggTFiel.getText());
    	
    	koordinator.receiveGuiValues(minDelay, maxDelay,
    								 minGGTProcesses, maxGGTProcesses, 
    								 timeout, 
    								 ggt);
    }
    
    public javax.swing.JTextArea getMessageTextArea() {
    	return messageTextArea;
    	
    }

	/**
	 * Adds a new pid to the ggtProzessTextArea.
	 * 
	 * @param pid the pid that is added.
	 */
	public void addPidToList(int pid) {
		ggtProzessTextArea.setText(ggtProzessTextArea.getText() + koordinator.getSlaveString(pid) + " \n");
		ggtProzessTextArea.setCaretPosition(ggtProzessTextArea.getDocument().getLength());
	}
	
	/**
	 * Removes the given pid from the ggtProzessTextArea
	 * 
	 * @param pid the pid that is to be removed
	 */
	public void removePidFromList(int pid){
		String pidstr = koordinator.getSlaveString(pid); 
		String oldtxtarea = ggtProzessTextArea.getText();
		StringBuffer newtxtarea = new StringBuffer();
		StringTokenizer tokenizer = new StringTokenizer(oldtxtarea);
		while(tokenizer.hasMoreElements()){
			String token = tokenizer.nextToken();
			if(!token.equalsIgnoreCase(pidstr)){
				newtxtarea.append(token +" \n");
			}
		}
		ggtProzessTextArea.setText(newtxtarea.toString());
		
	}

	public void clearMessageArea() {
		messageTextArea.setText("");
	}
}
